
const vscode = require('vscode');
const OSS = require('ali-oss');
const co = require('co');
const md5 = require('md5');
const { v1: uuid } = require('uuid');
const moment = require('moment');

const timesheet = moment().format('YYYYMMDD');

// 图片hash值
function getFileHash(fileName, digt = 16) {
    const arr = md5(uuid() + fileName).split('');
    arr.length = digt;
    return arr.join('');
}

const aliconfig = vscode.workspace.getConfiguration('upload_image')
const fileUrl = aliconfig.domain;
// 阿里云上传配置
const client = new OSS({
    region: aliconfig.region,
    accessKeyId: aliconfig.accessKeyId,
    accessKeySecret: aliconfig.accessKeySecret,
    bucket: aliconfig.bucket,
    timeout: 5000000,
});
// 图片上传
const imgUpload = (imgList) => {
    imgList.forEach((item, key) => {
        const imgFileArr = item.path.split('/');
        const imgName = imgFileArr[imgFileArr.length - 1];
        const imgExt = imgName.split('.')[1];
        const names = imgName.split('.')[0];
        co(function* () {
            const result = yield client.put(
                `${timesheet}/${names}.${getFileHash(item.path)}.${imgExt}`,
                `${item.path}`
            );
            if (result.res.status === 200) {
                const imageUrl = `${fileUrl}${result.name}`;
                addImageUrlToEditor(imageUrl)
            } else {
                console.log('图片上传失败')
            }
        }).catch(err => {
            console.log('图片上传失败')
        });
    });
}

// 将图片链接写入编辑器
function addImageUrlToEditor(url) {
    let editor = vscode.window.activeTextEditor
    if (!editor) {
        return
    }
    const { start, end, active } = editor.selection
    if (start.line === end.line && start.character === end.character) {
        // 在光标位置插入内容
        const activePosition = active
        editor.edit((editBuilder) => {
        editBuilder.insert(activePosition, url)
        })
    } else {
        // 替换内容
        const selection = editor.selection
        editor.edit((editBuilder) => {
            editBuilder.replace(selection, url)
        })
    }
}

module.exports = {
	imgUpload
};
